<?php

namespace addons\sum\controller\user;

use think\helper\Str;
use addons\sum\controller\Common;
use app\admin\model\sum\user\Coupon as UserCouponModel;

class Coupon extends Common
{

    protected $noNeedLogin = ['detail'];
    protected $noNeedRight = ['*'];

    public function index()
    {
        $user = auth_user();
        $type = $this->request->param('type', 'can_use');
        // 优惠券类型：can_use=可用，usedorsent=已使用或已赠送，expired=已过期

        $userCoupons = UserCouponModel::where('user_id', $user->id);

        if (in_array($type, ['can_use', 'usedorsent', 'expired'])) {
            $userCoupons = $userCoupons->{Str::camel($type)}();
        }

        $userCoupons = $userCoupons->order('id', 'desc')->paginate($this->request->param('list_rows', 10));

        $this->success('获取成功', $userCoupons);
    }

    public function detail()
    {
        $id = $this->request->param('id');
        $userCoupon = UserCouponModel::where('id',$id)->find();
        $this->success('获取成功', $userCoupon);
    }

    /**
     * 接收用户赠送的优惠券
     * @return void
     */
    public function receive()
    {
        $user = auth_user();
        $params = $this->request->only(['id']);
        if(!isset($params['id'])){
            $this->error('参数错误');
        }
        $userCouponOld=UserCouponModel::where('id', $params['id'])->find();
        if(!$userCouponOld){
            $this->error('为找到该优惠券');
        }
        if($userCouponOld['user_id']==$user['id']){
            $this->error('不能领取自己的优惠券');
        }
        if($userCouponOld['use_time']){
            $this->error('该优惠券已使用');
        }
        if($userCouponOld['send_time']){
            $this->error('该优惠券已被领取');
        }
        //处理旧券
        $userCouponOld->send_user_id=$user['id'];
        $userCouponOld->send_time=time();
        $userCouponOld->save();
        //处理新劵
        $userCouponNew=new UserCouponModel();
        $userCouponNew->user_id=$user['id'];
        $userCouponNew->name=$userCouponOld['name'];
        $userCouponNew->description=$userCouponOld['description'];
        $userCouponNew->amount=$userCouponOld['amount'];
        $userCouponNew->enough=$userCouponOld['enough'];
        $userCouponNew->use_end_time=strtotime($userCouponOld['use_end_time']);//因为这里获取的到期时间做日期格式处理了。存的时候要转成时间戳
        $userCouponNew->oper_id=$userCouponOld['user_id'];
        $userCouponNew->save();
        $this->success('领取成功');
    }
}
